function VarianceGammasRestricted

addpath('basic_functions');
addpath('../Data')

Nboot = 1000;
Nfactors = 3;

[Return,Z,IsF,Nt,Chars,CharsNames,~,~,~] = package_data_all_greeks;
Return = Return.ret_daily;
[N,T,L] = size(Z);

% remove Zhan, Han, Cao, and Tong (2022) 9
f = [find(strcmp(CharsNames,'Stock price')) find(strcmp(CharsNames,'CashFlowVar')) find(strcmp(CharsNames,'Cash to asset')) ...
    find(strcmp(CharsNames,'AnalystDisp')) find(strcmp(CharsNames,'1yr NewIss')) find(strcmp(CharsNames,'5yr NewIss')) ...
    find(strcmp(CharsNames,'Profit margin')) find(strcmp(CharsNames,'ROE')) find(strcmp(CharsNames,'ExternalFin'))  find(strcmp(CharsNames,'Z score'))];

Z(:,:,f) = [];
[N,T,L] = size(Z);

% construct W and X matrices that will be used for IPCA
W = NaN(L,L,T);
X = NaN(L,T);
for t = 1:T-1
    W(:,:,t) = squeeze(Z(IsF(:,t+1),t,:))'*squeeze(Z(IsF(:,t+1),t,:)) / Nt(t+1);
    X(:,t+1) = squeeze(Z(IsF(:,t+1),t,:))'*Return(IsF(:,t+1),t+1) / Nt(t+1);
    Return(~IsF(:,t+1),t+1) = NaN;
end
clear t;

% run IPCA
[G, F] = IPCA(X,W,Nt,Nfactors);
GammaBoot = NaN(Nboot,Nfactors,L);
for ell = 1:L
    [~,GammaBoot(:,:,ell)] = IPCA_char_pvalues(X,W,Nt,G,F,ell,Nboot);
end
save tables_outputs/GammaVariancesRestricted GammaBoot;

return